package com.itany.servlet;

import com.itany.ums.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet("/data")
public class DataServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行了DataServlet........");

        /**
         * 向request中存储数据
         */
        req.setAttribute("username","zhangsan");

        /**
         * 向session中存储数据
         */
        // 获取session
        HttpSession session = req.getSession();
        session.setAttribute("password","111");

        /**
         * 向application中存储数据
         */
        // 获取application
        // ServletContext application = req.getServletContext();
        ServletContext application = session.getServletContext();
        application.setAttribute("hobby","南京");


        /**
         * 存储对象数据
         */
        User user = new User();
        user.setId(1001);
        user.setName("tom");
        user.setAge(20);
        user.setSex("男");
        req.setAttribute("user",user);

        List<User> list = new ArrayList<>();
        list.add(new User(1001,"aaa",20,"男","吃饭"));
        list.add(new User(2004,"bbb",27,"男","吃饭"));
        list.add(new User(1007,"ccc",19,"女","吃饭"));
        list.add(new User(1003,"ddd",20,"男","吃饭"));
        session.setAttribute("users",list);

        // 存储日期
        req.setAttribute("birthday",new Date());

        req.getRequestDispatcher("test09.jsp").forward(req,resp);
    }
}
